/**
 * @author zhangqiang
 * @date   17/7/18
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Carousel, Toast, Popup, Picker, List, Switch} from 'antd-mobile'
import { createForm } from 'rc-form';

import {
	PassAddNumber,
	FooterAlert,
	FooterAlertMask,
	FooterRegionAlertMask,
	InputItem,
	Agreement,
	PassItem,
	GuideMask
} from '../../components/twHome'
import {
	twPersonalAddress,     //个人签注户籍
} from '../../components/common/addressData'
//通用组件
import {Title,FootNav} from '../../components/common'
import {
	passList,
	getCategory,
	provinceList,
	defaultAddress,
	subMitForm
} from  '../../actions/twHomeActions'
import {
	getAddAddress,
} from '../../actions/addAddressActions';
import '../../../styles/home.scss';
import common from '../../utils/common'
import getAddressCode from '../../utils/getTWAddressCode'
import style from './index.scss'

class Home extends Component {
	constructor(props) {
		super(props);
		this.state = {
			visaType: 1,  //1 个人 2团队 *跟后台参数同步  选择的下标
			visaName: '赴台个人旅游再次签注', //默认签注文字
			regionName: '六月一次',
			regionType: '1',
			times: 1,
			isCheck: false,  //发票
			isAgree: false,  //协议
			isShowAgree: false, //协议
			selectedIndex: 0,
			registerValue: [], //户籍地址
			hkDataType: [],  //香港类型数据源
			visaIndex: '',  //点击通行证签注的选项
			isShowMask: false,  //清远地区mask
			emsSitesList: [] //清远地区的紧急服务地址列表

		};
		this.isChecked = this.isChecked.bind(this);
	}

	componentWillMount(){
		//进入页面缓存赋值页面
		this.setState(
			Object.assign({},JSON.parse(sessionStorage.getItem('twCacheAllState')),
				sessionStorage.getItem('twAddPassSign')?{    //添加通行证标记
						selectedIndex: sessionStorage.getItem('twAddPassSign')?this.state.selectedIndex:''
					}:{}
			)
		)

	}

	componentDidMount() {
		common.setViewTitle('赴台签注办理');
		
		 //如果缓存有地址字体颜色改变深灰  户籍 **
		if(JSON.parse(sessionStorage.getItem('twCacheAllState'))&&JSON.parse(sessionStorage.getItem('twCacheAllState')).registerValue.length){
			document.querySelectorAll('.am-list-extra')[0].className='choiceColour';  //勾选后改变字体变深
		}
		//签注类别
		this.getRegionType()  
		//获取默认地址
		this.props.dispatch(defaultAddress({}))

		//通行证请求 silder走马灯数据
		this.props.dispatch(passList({},(result)=>{
			if(sessionStorage.getItem('twHandeListGetIntId')) {  //从代办列表 继续办理下一个通行证进入
				let slideType = JSON.parse(sessionStorage.getItem('tw_pay_data')).endorseInfoList;
				let isLookup = false;
				let isLookupArr = [];

				for (let i = 0; i < result.length; i++) {
					for (let y = 0; y < slideType.length; y++) {
						if (result[i].passCode == JSON.parse(slideType[y].endorseInfoObj).passCode) {
							isLookup = true;
							break;
						}
					}
					if (!isLookup) {
						isLookupArr.push(i);
						break;
					}
					isLookup = false;
				}
				setTimeout(()=>{
					this.setState({
						selectedIndex: isLookupArr[0]==undefined?-1:isLookupArr[0]  //如果全部相同,滑动到添加选项
					})
				},0)

			}
			if(sessionStorage.getItem('twHandleItem')){   //从代办列表条目 进入带入缓存
				let handLeItem = JSON.parse(sessionStorage.getItem('twHandleItem'));		
				for (let i = 0;i < this.props.twPassList.length;i++) {
					if(this.props.twPassList[i].passCode == handLeItem.orderEndorsementTw.passCode){
						setTimeout(()=>{
							this.setState({
								selectedIndex: i
							})
						},0)
					}
				}

				//获得户籍地址数据
				let getCity = {
					bizProvinceId: 440000,
					bizType: handLeItem.orderEndorsementTw.type //户籍请求状态和签注状态一样
				}
				this.getRegisterData(getCity)

				let addressArr = getAddressCode.getLookUpCode(handLeItem.orderEndorsementTw.birthPlace); //返回数组的形式
				
				this.setState({
					registerValue: addressArr,
					isAgree: true,
					isCheck: handLeItem.orderEndorsementTw.needInvoice
				})
				
				try{
					document.querySelector('.am-list-extra').className = 'choiceColour';					
				}catch(err){}

				let  chargeRuleList = [
					{
						"id": "2",
						"category": 3,
						"bizProvinceId": 440000,
						"destName": "台湾",
						"type": 1,
						"typeName": "个人旅游",
						"typeNameJc": "赴台个人旅游再次签注",
						"times": 1,
						"timesName": "六月一次",
						"endorseFee": 1500,
						"serviceLocalFee": 2500,
						"serviceOtherFee": 4500,
						"serviceOutsideFee": 4500,
						"useFlag": 1,
						"createTime": 1483718400000,
						"updateTime": 1499011200000
					},
					{
						"id": "1",
						"category": 3,
						"bizProvinceId": 440000,
						"destName": "台湾",
						"type": 2,
						"typeName": "团队旅游",
						"typeNameJc": "赴台团队旅游再次签注",
						"times": 1,
						"timesName": "六月一次",
						"endorseFee": 1500,
						"serviceLocalFee": 2500,
						"serviceOtherFee": 4500,
						"serviceOutsideFee": 4500,
						"useFlag": 1,
						"createTime": 1483977600000,
						"updateTime": 1499011200000
					}
				];

				for(let y=0;y<chargeRuleList.length;y++){
					if(chargeRuleList[y].type == handLeItem.orderEndorsementTw.type){
						this.setState({
							visaType: y+1,
							visaName: chargeRuleList[y].typeNameJc
						})
						break;
					}
				}
			}else{
				//获得户籍地址数据
				let getCity = {
					bizProvinceId: 440000,
					bizType: this.state.visaType //户籍请求状态和签注状态一样
				}
				this.getRegisterData(getCity)
			}

		}))
	}

	componentWillUnmount() {
		Popup.hide(); //防止用户点击弹框，点击返回弹框没有消失的bug
		sessionStorage.setItem('twCacheAllState',JSON.stringify(this.state))
		sessionStorage.removeItem('twAddPassSign')  //通行证页面标记
		sessionStorage.removeItem('twHandleItem')  //办理列表标记
		sessionStorage.removeItem('twHandeListGetIntId')  //办理列表点击办理下一个通行证标记
	}

	//获取户籍地址数据
	getRegisterData(getCity) {
		//获取户籍地区数据
		this.props.dispatch(provinceList(getCity))
	}
	/*
	*   选择签注类别签注种类
	*    个人  团队
	* */

	getRegionType(){  
		this.props.dispatch(getCategory({}))
	}

	//获取当前选中的车辆
	getCurrentCar(index){
		this.setState({
			selectedIndex: index
		})
	}

	/*
	*   选择通行证签注类别 mask
	*   timesName 签注种类
	*   typeNameJc 签注类别
	*   type 签注类型 1  2
	*   bizProvinceId  地区编码
	* */
	showVisaMask(){
		let props = {
			visaType: this.state.visaType,
			visaList: this.props.twVisaList,
			choose: (type,typeNameJc,times,timesName,bizProvinceId) => {
				/*
				*  切换签注类别时所有状态恢复默认值，地区取后台数据
				* */
				this.setState({
					regionName: timesName,
					visaName: typeNameJc,
					visaType: type,
					bizProvinceId: bizProvinceId,
					times: times,
					registerValue: [],  //从个人游到夫妻游 户籍清空颜色变浅会
					regionValue: [],  //组织地清空
				});

				//获得户籍地址数据
				let getCity = {
					bizProvinceId: 440000,
					bizType: type //户籍请求状态和签注状态一样
				}
				this.getRegisterData(getCity)

				try{
					document.querySelector('.choiceColour').className='am-list-extra';
					document.querySelector('.am-list-extra').innerHTML='请选择户籍';
				}catch (err){}
				Popup.hide(); //隐藏
			}
		};
		const y = scrollY
		Popup.show(<FooterAlertMask {...props}/>,{animationType: 'slide-up'});
		scrollTo(undefined, y)
	}

	/*
	*  提交表单，办理订单
	* */
	subMitForm(toUrl) {
		let state = this.state,
			cacheAddress;
		if(!this.props.isShowChice){
			cacheAddress = JSON.parse(sessionStorage.getItem('choiceAddress'))
		}else {
			cacheAddress = this.props.twDefaultAddress&&this.props.isShowChice? this.props.twDefaultAddress:
				JSON.parse(sessionStorage.getItem('choiceAddress'))?JSON.parse(sessionStorage.getItem('choiceAddress')):'';  //进入地址列表缓存的地址信息  选择地址的缓存

			sessionStorage.setItem('choiceAddress',JSON.stringify(cacheAddress))
		}
		let currentPass = this.props.twPassList[this.state.selectedIndex]; //当前证件信息 null为没有通行证，不滑动默认取第0个
		
		/*
		*   表单校验
		* */

		let idCardRule2= /^[0-9]{17}([0-9]|X|x)$/,
			creditCode1= /^[0-9a-zA-Z]{9,18}$/,
			nameRule1= /^[\u4e00-\u9fa5]{2,12}$/;

		if(currentPass == undefined){
			Toast.info('请添加通行证',1)
			return;
		}
		if(!state.registerValue[0]){
			Toast.info('请选择户籍所在地',1);
			return;
		}else if(!cacheAddress.contactName){
			Toast.info('请选择收件人信息',1);
			return;
		}else if(!state.isAgree){
			Toast.info('请阅读并同意《台湾通行证签注办理须知》',1);
			return;
		}

		let address={
			id: cacheAddress.provinceId,  //地址id，数据库主键标识
			provinceId: cacheAddress.provinceId,   //省份id
			cityId:cacheAddress.cityId, //地市id
			countyId: cacheAddress.countyId,//区县id  441825 不能办理
			street: cacheAddress.street, //街道详细地址
			fullAddr: cacheAddress.fullAddr, //'广东省清远市 连山壮族瑶族自治县 我们自己都江堵救灾', //完整地址
			contactName: cacheAddress.contactName, //收件人
			cellNum: cacheAddress.cellNum  //收件人联系号码

		};

		let enObj = {
			type: state.visaType,  
			timesName: state.regionName,    
			typeName: state.visaName,
			passId: currentPass.id, //证件id,
			passCode: currentPass.passCode, //证件号码
			passName: currentPass.passName,  //证件人名称
			passNameX: currentPass.passNameX,  //证件人名称，姓
			passNameM: currentPass.passNameM,  //证件人名称，名
			bizProvinceId: state.bizProvinceId,  //签注类型省份ID
			provinceId: state.registerValue[0].split(',')[1], //省份ID, //省份ID
			cityId: state.registerValue[1].split(',')[1], //户籍所属城市ID
			birthday: currentPass.birthday, //生日
			validateEnd: currentPass.validateEnd, //有效期
			birthPlace: state.registerValue[0].split(',')[0]+state.registerValue[1].split(',')[0], //户籍所在地+++
			birthCode: 18, //this.data.addressCode,  //户籍数据里的 code
			times: state.times,
			linkTel: cacheAddress.cellNum, //联系电话
			needInvoice: state.isCheck?1:0, //是否需要发票  1-需要 0-不需要
		};
		let postData={
			endorseInfoList: [{
				"endorseInfoObj": JSON.stringify(enObj),
				"address": JSON.stringify(address)
			}]
		};

		var formResult = {
			objStr: JSON.stringify(postData)
		};
		sessionStorage.setItem('tw_pay_data',JSON.stringify(postData));  //缓存支付页面用
		
		this.props.dispatch(subMitForm(formResult,(res)=>{
			if(!res.canHandler){   //清远市某些地区不能办理，提示mask
				this.setState({
					emsSitesList: res.emsSites,
					isShowMask: true
				})
			}else {
				sessionStorage.setItem('tw_checkout_success_data',JSON.stringify(res)); //支付页面的数据
				setTimeout(()=>{
					this.toUrl(toUrl)
				},50)
			}
		}))

		}

		/*
		*   是否需要发票
		* */
		isChecked(checked){
			this.setState({
				isCheck: checked
			});
		}

		/*
		*   是否同意协议
		* */
		isAgreeState(){
			this.setState({
				isAgree: !this.state.isAgree
			});
		}

		/*
		*   显示协议文案mask
		* */
		isShowAgreement(){
			this.setState({
				isShowAgree: !this.state.isShowAgree
			});
		}

		toUrl(url) {
			this.context.router.push(url);
		}

		//构建通行证走马灯
		structureSlider(){
			let data = [];
			for(let i=0;i<this.props.twPassList.length;i++){
				if(this.props.twPassList){
					data.push(<PassItem res={this.props.twPassList[i]} key={i} index={i} currentIndex={this.state.selectedIndex}/>)
				}
			}
			//添加通行证入口
			data.push(<PassAddNumber key={this.props.twPassList.length}/>)
			return data
		}

		//隐藏清远地区提示mask
		hideMask(){
			this.setState({
				isShowMask: !this.state.isShowMask
			})
		}

		toAddressList(){
			sessionStorage.setItem('scrollTop',document.body.scrollTop)
			setTimeout(()=>{
				this.toUrl('addressList')
			},0)

		}

		render() {
			let cacheAddress,
				visaType = this.state.visaType,
				addressStatus = false;

				if(!this.props.isShowChice){
					cacheAddress = JSON.parse(sessionStorage.getItem('choiceAddress'))
				}else {
					cacheAddress = this.props.twDefaultAddress&&this.props.isShowChice? this.props.twDefaultAddress:
					JSON.parse(sessionStorage.getItem('choiceAddress'))?JSON.parse(sessionStorage.getItem('choiceAddress')):'';  //进入地址列表缓存的地址信息  选择地址的缓存
		
					sessionStorage.setItem('choiceAddress',JSON.stringify(cacheAddress))
				}

			const { getFieldProps } = this.props.form;
			return (
			<div>
			<div className={style.home}>
				<div className={style.sliderTitle}>选择通行证</div>
				<div className={style.sliderContainer}>
					<div className={style.carouselContainer}>
						<Carousel className="my-carousel"
							autoplay={false}
							dots ={false}
							infinite
							selectedIndex={this.state.selectedIndex}
							swipeSpeed={35}
							beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}  //切换面板前的回调函数
							afterChange={index => {   //切换面板后的回调函数
								this.getCurrentCar(index)
							}}
						>
							{
								this.structureSlider()
							}
						</Carousel>
					</div>
				</div>

				<div style={{height: '.24rem'}}></div>

				<Title text='签注信息' isLine={true}/>
				<div className={style.passTypeCheck} onClick={()=> {this.showVisaMask()}}>
					<div className={`${style.visaLine} border_bottom_1`} >
						<span className={style.visaCategory}>签注类别</span>
						<span>{this.state.visaName}</span>
						<img className={style.iconToRight} src="./images/icon_to_r.png" alt=""/>
					</div>
				</div>
			

				{/* 地址组件 start */}
				<div className="register">
					<div className={style.pickerLine}>
						<Picker extra="请选择户籍" data={this.props.twProvinceList}  //this.props.twProvinceList twPersonalAddress.value
							format={(values) => { { return values.join(''); } }}
							title="选择地区"
							value={this.state.registerValue}
							onChange={(v)=>{
								let bizIndex;
								try {
									document.querySelectorAll('.am-list-extra')[0].className='choiceColour';  //勾选后改变字体变深
								} catch(error) {}
								this.setState({registerValue: v})					
							}}
						>
							<List.Item arrow="horizontal"><span style={{fontSize: '.32rem'}}>户&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;籍</span></List.Item>
						</Picker>
						<img className={style.iconToRight} src="./images/icon_to_r.png" alt=""/>
					</div>
				</div>
				{/* 地址组件 end */}
				<div className={style.regionBox}>
					<div className={style.regionType}>
						<div className={style.regionTag}>签注种类</div>
						<div className={style.regionStyle}>{this.state.regionName}</div>
					</div>
				</div>
				<div style={{height: '.24rem'}}></div>
				<div className={style.consigneeBox}>
					<img className={style.separateLine} src="./images/line.png" alt=""/>
					<Title text='收件人信息' isLine={true}/>
					<div onClick={()=>{this.toAddressList()}}>
						<div className={style.address}>
							<img className={style.map} src="./images/map.png" alt=""/>
							<div className={style.addAddress}>{
								cacheAddress&&cacheAddress.fullAddr!=''?cacheAddress.contactName+' '+cacheAddress.cellNum:'添加收件人信息'
							}</div>
							<img className={style.iconToRight} src="./images/icon_to_r.png" alt=""/>
						</div>
									{/*中山和东莞没有区传给后台null+cacheAddress.street*/}
							{
								cacheAddress&&cacheAddress.fullAddr!=''?<div className={style.fullAddress}>{cacheAddress.fullAddr.replace(null,'')}</div>:null
							}
				</div>
				</div>

				<div style={{height: '.24rem'}}></div>

				<div className="sliderBox">
					<div>
						<List.Item
							extra={<Switch
							checked = {this.state.isCheck}
							onChange={(checked) =>{this.isChecked(checked)}}
							/>}
						>签注发票</List.Item>
					</div>
				</div>
				<div className={style.invoice}>(签注发票由公安出入境部门提供)</div>
				<div style={{height: '.60rem'}}></div>
				<div className={style.agreeBox}>
					<span className={style.agreeEnlarge} onClick={()=>{this.isAgreeState()}}>
						<img className={style.agree} src={this.state.isAgree?'./images/agree.png':'./images/noCheck.png'} alt=""/>
						<span className={style.determine}>同意</span>
					</span>
					<span className={style.agreeBtn} onClick={()=>{this.isShowAgreement()}}>《台湾通行证签注办理须知》</span>
				</div>

				<div className={style.btnBox}>
					<button className={style.handle} type='button' onClick={()=>{this.subMitForm('twPayment')}}>立即办理</button>
					<button className={style.preservation} type='button' onClick={()=>{this.subMitForm('twHandleList')}}>保存，并办理下一个</button>
				</div>

				<div className={style.brief}>
					{/* <img className={style.footLogo} src="./images/img_logo_police.png" alt=""/> */}
					<p className={style.logoMsg}>本服务由中国邮政速递物流提供</p>
				</div>

				{/*协议--start*/}
				<Agreement isShow={this.state.isShowAgree} visaType={'tw'} onClick={()=>{this.isShowAgreement()}}/>
				{/*协议--end*/}

				{/*清远地区不能办理证件 mask start*/}

				<GuideMask
					isShowMask={this.state.isShowMask}
					onClick={()=>this.hideMask()}
					emsSitesList={this.state.emsSitesList}
				/>

				{/*清远地区不能办理证件 mask end*/}


			</div>
			{/*底部导航菜单 start*/}
			<FootNav data={{footNavType:'tw'}}/>
			{/*底部导航菜单 end*/}
			</div>
		)
		}
	}

//使用context
Home.contextTypes = {
    router: React.PropTypes.object.isRequired
};

Home.defaultProps = {
	twPassList:[],
	twVisaList: [],
	twProvinceList:[],
	twDefaultAddress: {
		fullAddr:'',
		street:''
	}
};

function mapStateToProps(state) {
	return Object.assign({}, state.twPassList,state.twVisaList,state.addressList,state.twDefaultAddress);
}

const TestWrapper = createForm()(Home);
export default connect(mapStateToProps)(TestWrapper);

